const regList = {
  mobile: /^1[3456789]\d{9}$/,
  idCard: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
}

export default function verify(form = {}, options = {}) {
  for (const key of Object.keys(options)) {
    const target = form[key]
    const option = options[key]
    const targetType = Object.prototype.toString.call(target).slice(8, -1)
    const regType = Object.prototype.toString.call(option.reg).slice(8, -1)
    if (targetType === 'Object') {
      verify(target, option.children)
    } else if (targetType === 'Array') {
      if (option.require && !target[0]) {
        fail(option.require)
      } else {
        const { require, reg, error } = option.children || option
        const childrenRegType = Object.prototype.toString.call(reg).slice(8, -1)
        if (require && !target[0]) fail(require)
        for (const i of target) {
          const iType = Object.prototype.toString.call(i).slice(8, -1)
          if (['Object', 'Array'].includes(iType)) {
            verify(i, option.children)
          } else {
            if (!reg) continue
            if (childrenRegType === 'String') reg = regList[reg]
            if (childrenRegType === 'Function' && !reg(i)) fail(error)
            if (['RegExp', 'String'].includes(childrenRegType) && !reg.test(i)) fail(error)
          }
        }
      }
    } else {
      if (option.require && !target && target !== 0 && target !== false) fail(option.require)
      if (option.reg && target !== '') {
        if (regType === 'String') option.reg = regList[option.reg]
        if (regType === 'Function' && !option.reg(target)) fail(option.error)
        if (['RegExp', 'String'].includes(regType) && !option.reg.test(target)) fail(option.error)
      }
    }
  }
}

function fail(msg = '验证失败') {
  uni.showModal({
    title: '提示',
    content: msg,
    showCancel: false
  })
  throw msg
}
